import { Button, Table, Input, Modal, Space, message } from 'antd';
import React, { useState, useEffect } from 'react';
import '../PrescriptionIssuance/PrescriptionIssuance.css';
import axios from 'axios';

const App = () => {
    const columns = [
        {
            title: '药品名称',
            dataIndex: 'drugsname',
        },
        {
            title: '药品图片',
            dataIndex: 'img',
            render: (url) => {
                if (url && url.startsWith('http://www.bingo1440.top:21001')) {
                    url = url.replace('http://www.bingo1440.top:21001', 'http://8.148.7.123:8000');
                }
                return url ? (
                    <img
                        src={url}
                        alt="药品图片"
                        style={{ width: '40px', height: '40px' }}
                    />
                ) : null;
            }
        },
        {
            title: '药品规格',
            dataIndex: 'sort',
        },
        {
            title: '药品单价',
            dataIndex: 'price',
        },
        {
            title: '药品数量',
            dataIndex: 'count',
            render: (record, key) => <div className='countBox'>
                <Button type="primary" danger onClick={() => handleDecrease(key.id)}>
                    -
                </Button>
                <div style={{ margin: '0 8px', width: '40px', textAlign: 'center' }}>{record}</div>
                <Button type="primary" onClick={() => handleIncrease(key.id)}>
                    +
                </Button>
            </div>
        },
        {
            title: '有效期',
            dataIndex: 'endtime',
            render: (text) => <span>{text}</span>
        },
        {
            title: '用量备注',
            dataIndex: 'type',
        },
        {
            title: '操作',
            dataIndex: 'canDo',
            render: (text, record) => <div className='one_del' onClick={() => handleDelete(record.id)}></div>
        },
    ];

    //单个删除
    const handleDelete = async (id) => {
        //console.log(id);
        const responseDelOne = await axios.get(`http://8.148.7.123:8000/drugs/del?id=${id}`);
        window.location.reload();
    };

    //选中的keyid值获取
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    const start = async () => {
        showModal();
    };
    const onSelectChange = (newSelectedRowKeys) => {
        //console.log('ids数组 ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };
    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;

    //药品数据
    const [data, setData] = useState([]);

    //查询输入
    const [searchText, setSearchText] = useState([]);

    // 过滤后的表格数据
    const [filteredData, setFilteredData] = useState([]);

    //格式化时间
    function formatDateTime(isoString) {
        const date = new Date(isoString);
        const year = date.getFullYear();
        const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，所以加1
        const day = date.getDate().toString().padStart(2, '0');
        return `${year}-${month}-${day}`;
    }

    // 处理查询输入
    const handleSearch = (e) => {
        setSearchText(e.target.value);
    };

    // 过滤表格数据
    const handleFindBtn = () => {
        const filtered = data.filter(item => item.drugsname.toLowerCase().includes(searchText.toLowerCase()));
        setFilteredData(filtered); // 更新过滤后的数据状态
    }

    //post请求参数
    const newDrugInfo = {
        name: "测试药品", // 药品耗材名称
        sort: "一次性器材", // 药品分类
        type: "100", // 规格
        starttime: "2022-12-25", // 生产日期
        endtime: "2023-12-26", // 有效日期
        count: "001", // 入库数量
        price: "100", // 药品耗材价格
        img: "16678110069850.webp" // 药品耗材图片名称
    };

    //添加药品 -- 基本框架逻辑
    const handleAdd = async () => {
        try {
            const responseAdd = await axios.post('http://8.148.7.123:8000/drugs/add', newDrugInfo);
            //console.log(responseAdd);
            window.location.reload();
        } catch (error) {
            console.error('Error adding drug: ', error);
        }
    };

    //提示框 -- 全部删除
    const [isModalOpen, setIsModalOpen] = useState(false);

    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk = async () => {
        setIsModalOpen(false);
        if (hasSelected) {
            setLoading(true);
            try {
                // 构建包含选中药品 id 的 URL
                const ids = selectedRowKeys;//selectedRowKeys
                //console.log(ids);
                const responseDel = await axios.post(`http://8.148.7.123:8000/drugs/batchdel`, { ids: ids });
                window.location.reload();
                //console.log(responseDel);

            } catch (error) {
                console.error('Error deleting drugs: ', error);
            } finally {
                setLoading(false);
                setSelectedRowKeys([]); // 清空选中的行
            }
        }
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    //计算总价
    const [totalPrice, setTotalPrice] = useState(0);

    const calculateTotalPrice = (data) => {
        let total = 0;
        data.forEach(item => {
            const price = parseFloat(item.price);
            const count = parseInt(item.count, 10);
            total += price * count;
        });
        setTotalPrice(total);
    };

    // 增加和减少数量的函数 x   
    // 增加数量
    const handleIncrease = (id) => {
        console.log(id);
        const newData = data.map(item => {
            if (item.id === id) {
                item.count++;
                // console.log(item.id);
                // console.log(item.drugsname);
                // console.log(item.sort);
                // console.log(item.type);
                // console.log(item.starttime);
                // console.log(item.endtime);
                // console.log(item.count);
                // console.log(item.price);
                // console.log(item.img);
                const response = axios.get(
                    //?id=${item.id}&name=${item.drugsname}&sort=${item.sort}&type=${item.type}&starttime=${item.starttime}&endtime=${item.endtime}&count=${item.count}&price=${item.price}&img=${item.img}
                    `http://8.148.7.123:8000/drugs/edit`, {
                    id: item.id,
                    name: item.drugsname,
                    sort: item.sort,
                    type: item.type,
                    starttime: item.starttime,
                    endtime: item.endtime,
                    count: item.count,
                    price: item.price,
                    img: item.img
                });//

                console.log(response);

            }
            return item;
        });
        setData(newData);
    };

    // // 减少数量
    const handleDecrease = (id) => {
        console.log(id);
        const newData = data.map(item => {
            if (item.id === id && item.count > 1) {
                item.count--;
            }
            return item;
        });
        setData(newData);
    };

    //获取医生名字
    const [name, setName] = useState('');

    //开具处方
    const handlePrescription = async () => {
        try {
            // 获取医生ID
            const dr_id = localStorage.getItem('dr_id');
            if (!dr_id) {
                console.error('Doctor ID not found.');
                return;
            }

            // 构建处方信息数组
            const prescriptionInfoArray = data.map(item => ({
                drugsname: item.drugsname,
                type: item.sort,
                starttime: newDrugInfo.starttime, // 假设所有药品的开始时间相同
                endtime: newDrugInfo.endtime, // 假设所有药品的有效期相同
                count: item.count,
                price: item.price,
                img: item.img,
                other: '一日一次，一次一粒' // 假设所有药品的用量备注相同
            }));

            // 计算处方总价
            const totalPrice = prescriptionInfoArray.reduce((sum, item) => {
                return sum + parseFloat(item.price) * parseInt(item.count, 10);
            }, 0);

            // 发送处方信息到服务器
            const response = await axios.post('http://8.148.7.123:8000/recipel/add', {
                doctorid: dr_id,
                recipe: prescriptionInfoArray,
                price: totalPrice
            });

            // 处理响应
            if (response.status === 200) {
                console.log('Prescription issued successfully.');
                // 可以在这里添加一些用户反馈，比如弹窗提示处方已开具
                success();
            } else {
                console.error('Failed to issue prescription.');
            }
        } catch (error) {
            console.error('Error issuing prescription: ', error);
        }
    };

    //获取医药列表数据
    useEffect(() => {
        const fetchData = async () => {
            try {
                //获取医药物品数据
                const response = await axios.get('http://8.148.7.123:8000/drugs/list?page=1&size=100');
                const newData = response.data.data.map(item => ({
                    ...item,
                    key: item.id, // 假设每个药品有一个唯一的id
                    endtime: formatDateTime(item.endtime),
                }));
                console.log(response);
                setData(newData);
                setFilteredData(newData)
                calculateTotalPrice(newData); // 计算总价

                //获取医生id及医生信息
                const dr_id = localStorage.getItem('dr_id')
                //console.log(dr_id);//15
                const responseDr = await axios.get(`http://8.148.7.123:8000/users/getbyid?id=${dr_id}`);
                //console.log(responseDr.data.data[0].name);
                setName(responseDr.data.data[0].name);
                //console.log(response.data.data);
            } catch (error) {
                console.error('Error fetching data: ', error);
            }
        };
        fetchData();
    }, []); // 空依赖数组确保仅在组件加载时运行

    //提示
    const success = () => {
        message.success('处方开具成功');
    };

    return (
        <div>
            <div
                style={{
                    marginBottom: 16,
                }}
            >
                <div className='top_box'>
                    <div className='top_box_son'>
                        <Input placeholder='输入药品/器材/疫苗名称' onChange={handleSearch} className='inp' />
                        &emsp;&emsp;
                        <Button type="primary" onClick={handleFindBtn}>查询</Button>
                    </div>
                    <div>
                        <Button type="primary" onClick={handleAdd}>添加药品</Button>
                        &emsp;
                        <Button type="primary" onClick={start} disabled={!hasSelected} loading={loading}>
                            删除选中
                        </Button>
                    </div>
                </div>
                <span
                    style={{
                        marginLeft: 8,
                    }}
                >
                    {hasSelected ? `选择 ${selectedRowKeys.length} 个药品` : ''}
                </span>
            </div>
            <Table rowSelection={rowSelection} columns={columns} dataSource={filteredData} />
            <div className='boxBottom'>
                <div className='sumBox'>总价:{totalPrice}元</div>
                <div className='sumBox'>医生签名:{name}</div>
                <Button type="primary" onClick={handlePrescription}>开具处方</Button>
            </div>
            <Modal title="警告" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} okText="确认"
                cancelText="取消">
                <p>确定要删除选中吗?</p>
            </Modal>
        </div>
    );
};
export default App;